package com.fine.demo.keyboard

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.util.AttributeSet

class MKeyboardView : KeyboardView {

    private var mContext: Context? = null
    private lateinit var mPaint: Paint
    private lateinit var mRect: Rect
    private var keyboardType = -1

    private val TEXT_SIZE = 32f
    private val CN_TEXT_SIZE = 30f

    constructor(context: Context?, attr: AttributeSet?): super(context, attr){
        initKeyboardView(context)
    }

    constructor(
        context: Context?,
        attr: AttributeSet?,
        defStyleAttr: Int
    ): super(context, attr, defStyleAttr) {
        initKeyboardView(context)
    }

    private fun initKeyboardView(context: Context?) {
        this.mContext = context
        mRect = Rect()

        mPaint = Paint()
        mPaint.apply {
            textSize = TEXT_SIZE
            isAntiAlias = true
            color = Color.BLACK
            textAlign = Paint.Align.CENTER
            alpha = 255
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if(keyboard == null) {
            return
        }
        val keys = keyboard.keys
        if(keyboardType == 0) {     //数字键盘
            drawKeywordNumber(keys, canvas)
        } else if(keyboardType == 1) {      //英文键盘
            drawKeywordEnglish(keys, canvas)
        }
    }

    private fun drawKeywordNumber(keys: List<Keyboard.Key>, canvas: Canvas?) {
        for (key in keys) {
            drawKeyText(canvas, key)
        }
    }

    private fun drawKeywordEnglish(keys: List<Keyboard.Key>, canvas: Canvas?) {
        for (key in keys) {
            drawKeyText(canvas, key)
        }
    }

    private fun drawKeyText(canvas: Canvas?, key: Keyboard.Key) {
        val keyCode = key.codes[0]
        if(keyCode == -4
            || keyCode == -11
            || keyCode == 32) {    //删除键
            mPaint.textSize = CN_TEXT_SIZE
        } else {
            mPaint.textSize = TEXT_SIZE
        }
        if(key.label != null) {
            mPaint.getTextBounds(key.label.toString(), 0, key.label.toString().length, mRect)
            canvas?.drawText(key.label.toString(), (key.x + key.width / 2f), (key.y + key.height / 2f) + mRect.height() / 2f, mPaint)
        }
    }

    public fun setCurrentKeyboard(keyboardType: Int) {
        this.keyboardType = keyboardType
        invalidate()
    }
}